package com.naizhuai.util;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

/**
 * @author：lichenxi
 * @date 2018/1/5 16
 * email：525603977@qq.com
 * Fighting
 */
public class AutoClearedValue<T> {
    private T value;

    public  AutoClearedValue(Fragment fragment,T value){
       final  FragmentManager fragmentManager = fragment.getFragmentManager();
        fragmentManager.registerFragmentLifecycleCallbacks(
                new FragmentManager.FragmentLifecycleCallbacks() {
                    @Override
                    public void onFragmentDestroyed(FragmentManager fm, Fragment fragment) {
                        if (fragment==null){
                             AutoClearedValue.this.value=null;
                             fragmentManager.unregisterFragmentLifecycleCallbacks(this);
                        }
                    }
                }
        ,false);
    }

    public T get(){
        return value;
    }
    
    public static <T> T checkNotNull(T reference) {
        if(reference == null) {
            throw new NullPointerException();
        } else {
            return reference;
        }
    }
}
